package com.sz.biz.common.customer.service.impl;

import com.sz.biz.common.constants.ErrorCodes;
import com.sz.biz.common.customer.entity.CusCustomerOrderMessage;
import com.sz.biz.common.customer.service.CusCustomerOrderMessageService;
import com.sz.biz.common.customer.dto.CusCustomerOrderMessageDto;
import com.sz.biz.common.customer.dto.CustomerMessageDto;
import com.sz.biz.common.customer.dto.CustomerNoticeMessageStatus;
import com.sz.biz.common.customer.dto.CustomerNoticeMessageTypeEnum;
import com.sz.common.base.dao.ParamData;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.service.AbstractService;
import com.sz.common.base.utils.StringUtils;
import com.sz.common.core.system.entity.SysMail;
import com.sz.common.core.system.entity.SysSMS;
import com.sz.common.core.system.service.SysMailService;
import com.sz.common.core.system.service.SysSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Function: TODO: ADD FUNCTION <br>
 * Author: Johnboy <br>
 * Date: 2017-08-28 15:45:00
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class CusCustomerOrderMessageServiceImpl extends AbstractService implements CusCustomerOrderMessageService {

    @Autowired
    private SysMailService sysMailService;

    @Autowired
    private SysSmsService sysSmsService;

    @Override
    protected String getMapperNamespace() {
        return "CusCustomerOrderMessageMapper";
    }

    @Override
    public void save(CusCustomerOrderMessage cusCustomerOrderMessage) {
        if (cusCustomerOrderMessage != null) {
            validateData(cusCustomerOrderMessage);
            this.dao.save(getSqlName("insertSelective"), cusCustomerOrderMessage);
        }
    }

    @Override
    public int querySendTimes(String businessType, String orderNo, String orderStatus) {
        ParamData paramData = new ParamData();
        paramData.put("businessType", businessType);
        paramData.put("orderNo", orderNo);
        paramData.put("orderStatus", orderStatus);
        List<CusCustomerOrderMessage> list = this.dao.findForList(getSqlName("querySendTimes"), paramData, CusCustomerOrderMessage.class);
        if (list == null || list.size() == 0) {
            return 0;
        }
        else {
            return list.get(0).getSendTimes();
        }
    }

    @Override
    public List<CusCustomerOrderMessageDto> queryOrdersResult(List<CusCustomerOrderMessageDto> dto) {
        long start = System.currentTimeMillis();
        List<CusCustomerOrderMessageDto> list = new ArrayList<>();
        for (CusCustomerOrderMessageDto messageDto : dto) {
            CusCustomerOrderMessageDto result = queryLastResult(messageDto.getOrderNo(), messageDto.getOrderStatus(), messageDto.getBusinessType());
            if (result != null) {
                list.add(result);
            }
        }
        long end = System.currentTimeMillis();
        System.out.println(end-start);
        return list;
    }

    @Override
    public void updateOrderNoByOrderNo(String oldOrderNo, String newOrderNo) {
        if(StringUtils.isEmpty(oldOrderNo)||StringUtils.isEmpty(newOrderNo)){
            throw Exceptions.bizException(ErrorCodes.ERROR_COMMON,"订单号不能为空！");
        }
        ParamData pd = new ParamData();
        pd.put("newOrderNo",newOrderNo);
        pd.put("oldOrderNo",oldOrderNo);
        dao.update(getSqlName("updateOrderNoByOrderNo"), pd);
    }

    @Override
    public CusCustomerOrderMessageDto queryLastResult(String orderId, String orderStatus, String bussinessType) {
        ParamData pd = new ParamData();
        pd.put("orderNo", orderId);
        pd.put("orderStatus", orderStatus);
        pd.put("businessType", bussinessType);
        int sendTimes = querySendTimes(bussinessType, orderId, orderStatus);
        pd.put("sendTimes",sendTimes);
        List<CusCustomerOrderMessage> cusCustomerOrderMessages = this.dao.findForList(getSqlName("selectByOrderIdAndOrderStatus"), pd, CusCustomerOrderMessage.class);
        CusCustomerOrderMessageDto cusCustomerOrderMessageDto = new CusCustomerOrderMessageDto();
        List<CustomerMessageDto> customerMessageDtos = new ArrayList<>();
        for (CusCustomerOrderMessage cusCustomerOrderMessage : cusCustomerOrderMessages) {
            cusCustomerOrderMessageDto.setOrderNo(cusCustomerOrderMessage.getOrderNo());
            cusCustomerOrderMessageDto.setOrderStatus(cusCustomerOrderMessage.getOrderStatus());
            cusCustomerOrderMessageDto.setCusUserId(cusCustomerOrderMessage.getCusUserId());
            cusCustomerOrderMessageDto.setCustomerId(cusCustomerOrderMessage.getCustomerId());
            cusCustomerOrderMessageDto.setBusinessType(cusCustomerOrderMessage.getBusinessType());
            CustomerMessageDto customerMessageDto = new CustomerMessageDto();
            if (CustomerNoticeMessageTypeEnum.EMAIL.getCode().equalsIgnoreCase(cusCustomerOrderMessage.getMessageType())) {
                SysMail sysMail = sysMailService.getMailById(cusCustomerOrderMessage.getRefMessageId());
                if (sysMail == null) {
                    customerMessageDto.setMessageStatus(CustomerNoticeMessageStatus.FAIL);
                }
                else {
                    if (sysMail.getIsSent()) {
                        customerMessageDto.setMessageStatus(CustomerNoticeMessageStatus.SUCCESS);
                    }
                    else {
                        if (sysMail.getRetry() < 10) {
                            customerMessageDto.setMessageStatus(CustomerNoticeMessageStatus.SUCCESS);
                        }
                        else {
                            customerMessageDto.setMessageStatus(CustomerNoticeMessageStatus.FAIL);
                        }
                    }
                }
            }
            if (CustomerNoticeMessageTypeEnum.SMS.getCode().equalsIgnoreCase(cusCustomerOrderMessage.getMessageType())) {
                SysSMS sysSMS = sysSmsService.getSmsById(cusCustomerOrderMessage.getRefMessageId());
                if (sysSMS == null) {
                    customerMessageDto.setMessageStatus(CustomerNoticeMessageStatus.FAIL);
                }
                else {
                    if (sysSMS.getIsSent()) {
                        customerMessageDto.setMessageStatus(CustomerNoticeMessageStatus.SUCCESS);
                    }
                    else {
                        if (sysSMS.getRetry() < 10) {
                            customerMessageDto.setMessageStatus(CustomerNoticeMessageStatus.SUCCESS);
                        }
                        else {
                            customerMessageDto.setMessageStatus(CustomerNoticeMessageStatus.FAIL);
                        }
                    }
                }
            }
            customerMessageDto.setMessageType(cusCustomerOrderMessage.getMessageType());
            customerMessageDto.setRefMessageId(cusCustomerOrderMessage.getRefMessageId());
            customerMessageDto.setCreateTime(cusCustomerOrderMessage.getCreateTime());
            customerMessageDtos.add(customerMessageDto);
        }
        cusCustomerOrderMessageDto.setCustomerMessageDtoList(customerMessageDtos);
        return cusCustomerOrderMessageDto;
    }


    private void validateData(CusCustomerOrderMessage cusCustomerOrderMessage) {
        if (cusCustomerOrderMessage != null) {
            if (StringUtils.isEmpty(cusCustomerOrderMessage.getCusUserId())) {
                throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "userId");
            }
            if (StringUtils.isEmpty(cusCustomerOrderMessage.getCustomerId())) {
                throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "customerId");
            }
            if (StringUtils.isEmpty(cusCustomerOrderMessage.getOrderNo())) {
                throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "orderNo");
            }
            if (StringUtils.isEmpty(cusCustomerOrderMessage.getMessageType())) {
                throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "messageType");
            }
        }
    }
}
